package com.leesche.zcsp.node.app.v1.controller.commet;

import com.leesche.zcsp.node.utils.UUIDGenerateUtil;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.model.PubCommet;
import com.leesche.zcsp.node.web.service.PubCommetService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;

/**
 * Created by kaider on 2016/11/22.
 * 设备吐槽
 */
@Controller
@RequestMapping("/app/v1/commet")
public class AppCommetController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AppCommetController.class);

    @Autowired
    private PubCommetService commetService;

    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    private Map<String,Object> add(HttpServletRequest request,
            PubCommet commet,@RequestParam(value = "file", required = false) MultipartFile file
    ){
        try {
            if(file==null){
                return WebResult.failure("请上传文件!").toMap();
            }
            String path = request.getSession().getServletContext().getRealPath("upload");
            String fileName = file.getOriginalFilename();
            System.out.println(fileName);
            String extName = fileName.substring(fileName.lastIndexOf("."));
            if(!WebUtils.checkIsImage(extName)){
                return WebResult.failure("必须是图片!").toMap();

            }
            fileName= UUIDGenerateUtil.generateUUID()+extName;
            File targetFile = new File(path, fileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            file.transferTo(targetFile);
            Long adminId = 1L;
            commet.setAdminid(adminId);
            commet.setCommetimage(fileName);
            commetService.insert(commet);

            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

}
